if( typeof console != 'undefined' ){ console.debug('edit.js'); }

GW.menu.tools = 
        { text: "Editing Tools",                                                        // GewWiki tools
            submenu: { id: 'idEditSubmenu',
                itemdata: [
                    { text: 'Save Page', id: 'idEditMI', disabled: false, onclick: { fn: function(){ GW.savePage(); }, scope: GW }},
                    { text: 'Show Properties', id: 'idPropertiesMI', disabled: false, onclick: { fn: function(){ GW.pageProperties.show();}, scope: GW }},
                    { text: 'New page', id: 'idNewMI', disabled: false, onclick: { fn: function(){ GW.newPage.show();}, scope: GW }},
                    { text: 'Log', onclick: { fn: GW.log.showHide, scope: GW.log }}
                ]
            }
        };
        
GW.pageOnLoad = function(){                                                     // onLoad
    GW.log.log( 'GW.pageOnLoad' );
    GW.configPage();                                                            // configure the page
    GW.pageProperties.init();
    GW.feature.initDialog();
    GW.marker.initDialog();
    GW.line.initDialog();
    GW.shape.initDialog();
    GW.displayFeaturePage.init();                                               // init feature page display facility
    GW.pageDiv.init();                                                          // init the page div for editing
    GW.mapDiv.init();                                                           // init the map div for editing
    window.onbeforeunload = GW.confirmUnload;                                   // setup to check if edit is unsaved on any exit
    GW.wait.hide();
};
GW.confirmUnload = function(){                                                  // confirm unload
    GW.dirty = GW.dirty || GW.rte.editor.editorDirty;
    if( GW.dirty ){
        var msg = 'You have unsaved changes.';
        return msg;
    }
    return;
};
GW.pageOnUnload = function(){                                                   // onUnload
    GW.log.log( 'GW.pageOnUnload' );
    GUnload();
};
GW.configPage = function(){                                                     // configure the page
    GW.div.leftright( 'idLeft', 'idMap' );
};
GW.pageDiv = {                                                                  // support idContent div
    init: function(){
        GW.rte.init();
    }
};
GW.mapDiv = {                                                                   // support idMap div
    date: new Date(),                                                           // date/time 
    timer: 0,                                                                   // movezoom timer
    query: '',                                                                  // our query object
    init: function(){
        GW.mapDiv.map = new GW.map( 'idMap', true );
        if( GW.hash.havehash() ){                                               // have some hash, so use it
            GW.hash.initLLZT( GW.lat, GW.lon, GW.zoom, GW.maptype);
            GW.mapDiv.map.setLLZT( GW.lat, GW.lon, GW.zoom, GW.maptype );
        } else if( GW.page['bboxNorth'] != null ){
            GW.mapDiv.map.setLLZTfromBB( GW.page['bboxNorth'],
                                GW.page['bboxSouth'],
                                GW.page['bboxEast'],
                                GW.page['bboxWest'],
                                GW.maptype );
        } else {
            GW.mapDiv.map.setLLZT( GW.lat, GW.lon, GW.zoom, GW.maptype );
        }
        GW.mapDiv.map.showFeatures( GW.page['features'], true );
    }
};
GW.feature = {                                                                  // feature add/delete support
    initDialog: function(){
        GW.feature.addDialog = new YAHOO.widget.Dialog("idAddFeatureDialog",
            { 
                postmethod: "none",
                fixedcenter : true,
                constraintoviewport: true,
                modal: true,
                visible : false, 
                buttons : [ { text:"Exit", handler: function(){this.cancel();}, isDefault:true } ]
            });
        GW.feature.addDialog.render(document.body);
    },
    showAddDialog: function(){
        GW.feature.addDialog.bringToTop();
        GW.feature.addDialog.show();
    }
};
GW.marker = {                                                                   // marker add/delete/edit support
    initDialog: function(){                                                     // init marker edit dialog
        GW.marker.editDialog = new YAHOO.widget.Dialog("idMarkerDialog",
            { 
                postmethod: "none",
                fixedcenter : true,
                constraintoviewport: true,
                modal: true,
                visible : false, 
                buttons : [ 
                    { text:"Exit", handler: function(){this.cancel();}, isDefault:true },
                    { text:"Delete", handler: GW.marker.editDelete, isDefault:false }
                ]
            });
        GW.marker.editDialog.render(document.body);
    },
    newMarker: function(){                                                      // create a new marker
        GW.feature.addDialog.hide();
        GW.dirty = true;
        var features = GW.page['features'];
        var p = GW.mapDiv.map.map.getCenter();                                  // the map's center
        var feature = { 
            ftype: GW.TYPE_ICON,
            icon: GW.ICON,
            point: [p.lat(), p.lng()],
            revision: GW.page['revision'],
            wikiTitle: GW.page['wikiTitle'] 
        };
        features.push( feature );
        GW.marker.edit( feature, null );
        return;
    },
    edit: function( feature, mapfeature ){                                      // edit/delete an existing feature
        GW.marker.editFeature = feature;                                        // save the feature and mapfeature
        GW.marker.editMapFeature = mapfeature;
        GW.marker.editDialog.bringToTop();                                      // display the marker edit dialog
        GW.marker.editDialog.show();
    },
    editSetIcon: function( icon ){                                              // icon clicked
        GW.marker.editDialog.hide();                                            // hide the dialog
        GW.marker.editFeature.icon = icon;                                      // set the new icon value
        if( GW.marker.editMapFeature != null ){                                 // editing the icon on an existing feature
            var ll = GW.marker.editMapFeature.getLatLng();                          // the marker may have been moved, so get it's current position
            GW.marker.editFeature.point = [ ll.lat(), ll.lng() ];                   // and save in the feature
            GW.mapDiv.map.map.removeOverlay( GW.marker.editMapFeature );            // delete the old marker from the map
        }
        GW.dirty = true;                                                        // mark the page as dirty
        GW.mapDiv.map.showFeature( GW.marker.editFeature, true );               // create a new feature with the new icon
        GW.marker.editFeature = null;                                           // clear the saved edit feature and mapfeature
        GW.marker.editMapFeature = null;
    },
    editDelete: function(){                                                     // delete exit from edit
        var r = confirm( 'Delete feature?' );
        if( r ){
            GW.marker.editDialog.hide();
            GW.mapDiv.map.map.removeOverlay( GW.marker.editMapFeature );        // actually delete the feature from the map
            GW.dirty = true;                                                    // mark the page as dirty
            GW.marker.editFeature = null;                                       // clear the saved edit feature and mapfeature
            GW.marker.editMapFeature = null;
        }
    }
};
GW.line = {                                                                     // line add/delete/edit support
    initDialog: function(){                                                     // init line edit dialog
        GW.line.editDialog = new YAHOO.widget.Dialog("idLineDialog",
            { 
                postmethod: "none",
                fixedcenter : true,
                constraintoviewport: true,
                modal: true,
                visible : false, 
                buttons : [ 
                    { text:"Exit", handler: function(){this.cancel();}, isDefault:true },
                    { text:"Delete", handler: GW.line.editDelete, isDefault:false }
                ]
            });
        GW.line.editDialog.render(document.body);
    },
    newLine: function(){                                                        // add a new line to the map
        GW.feature.addDialog.hide();
        GW.dirty = true;
        var features = GW.page['features'];
        var c = GW.mapDiv.map.map.getCenter();                                      // the map's center
        var bounds = GW.mapDiv.map.map.getBounds();                                 // the map's bounds
        var ne = bounds.getNorthEast();                                             // get the corners
        var sw = bounds.getSouthWest();
        var lat = c.lat();                                                          // default line through the center of the map
        var lngw = (sw.lng()-ne.lng())*0.66+ne.lng();                               // 2/3 west from east edge 
        var lnge = (sw.lng()-ne.lng())*0.33+ne.lng();                               // 1/3 west from east edge
        var feature = {
            ftype: GW.TYPE_POLYLINE,
            color: 'red',
            opacity: 1,
            width: 2,
            points: [[lat, lngw], [lat, lnge]],
            revision: GW.page['revision'],
            wikiTitle: GW.page['wikiTitle'] 
        };
        features.push( feature );
        GW.line.edit( feature, null );
        return;
    },
    edit: function( feature, mapfeature ){                                      // edit/delete an existing feature
        GW.line.editFeature = feature;                                          // save the feature and mapfeature
        GW.line.editMapFeature = mapfeature;
        GW.line.editDialog.bringToTop();                                        // display the marker edit dialog
        GW.line.editDialog.show();
    },
    editSetColor: function( color ){                                            // color clicked
        GW.line.editDialog.hide();                                              // hide the dialog
        GW.line.editFeature.color = color;
        if( GW.line.editMapFeature != null ){                                   // editing the color of an existing line
            GW.line.editMapFeature.setStrokeStyle({color:color});
        } else {                                                                // new line
            GW.mapDiv.map.showFeature( GW.line.editFeature, true );             // put the line on the map
        }
        GW.dirty = true;                                                        // mark the page as dirty
        GW.line.editFeature = null;                                             // clear the saved edit feature and mapfeature
        GW.line.editMapFeature = null;
    },
    editDelete: function(){                                                     // delete exit from edit
        var r = confirm( 'Delete line?' );
        if( r ){
            GW.line.editDialog.hide();
            GW.mapDiv.map.map.removeOverlay( GW.line.editMapFeature );          // actually delete the feature from the map
            GW.dirty = true;                                                    // mark the page as dirty
            GW.line.editFeature = null;                                         // clear the saved edit feature and mapfeature
            GW.line.editMapFeature = null;
        }
    }
};
GW.shape = {                                                                    // shape add/delete/edit support
    initDialog: function(){                                                     // init line edit dialog
        GW.shape.editDialog = new YAHOO.widget.Dialog("idShapeDialog",
            { 
                postmethod: "none",
                fixedcenter : true,
                constraintoviewport: true,
                modal: true,
                visible : false, 
                buttons : [ 
                    { text:"Exit", handler: function(){this.cancel();}, isDefault:true },
                    { text:"Delete", handler: GW.shape.editDelete, isDefault:false }
                ]
            });
        GW.shape.editDialog.render(document.body);
    },
    newShape: function(){                                                       // add a new shape to the map
        GW.feature.addDialog.hide();
        GW.dirty = true;
        var features = GW.page['features'];
        var c = GW.mapDiv.map.map.getCenter();                                      // the map's center
        var bounds = GW.mapDiv.map.map.getBounds();                                 // the map's bounds
        var ne = bounds.getNorthEast();                                             // get the corners
        var sw = bounds.getSouthWest();
        // now need three points
        var lat1 = (ne.lat()-sw.lat())*0.66+sw.lat();                               // 2/3 north from south edge
        var lng1 = c.lng();                                                         // in the middle of the map
        var lngw = (sw.lng()-ne.lng())*0.66+ne.lng();                               // 2/3 west from east edge
        var lnge = (sw.lng()-ne.lng())*0.33+ne.lng();                               // 1/3 west from east edge
        var latew= (ne.lat()-sw.lat())*0.33+sw.lat();                               // 1/3 north from south
        var feature = {
            ftype: GW.TYPE_POLYGON,
            color: 'red',
            opacity: 1,
            width: 2,
            points: [[lat1,lng1], [latew, lngw], [latew, lnge], [lat1,lng1]],
            revision: GW.page['revision'],
            wikiTitle: GW.page['wikiTitle'] 
        };
        features.push( feature );
        GW.shape.edit( feature, null );
        return;
    },
    edit: function( feature, mapfeature ){                                      // edit/delete an existing feature
        GW.shape.editFeature = feature;                                         // save the feature and mapfeature
        GW.shape.editMapFeature = mapfeature;
        GW.shape.editDialog.bringToTop();                                       // display the marker edit dialog
        GW.shape.editDialog.show();
    },
    editSetColor: function( color ){                                            // color clicked
        GW.shape.editDialog.hide();                                             // hide the dialog
        GW.shape.editFeature.color = color;
        if( GW.shape.editMapFeature != null ){                                  // editing the color of an existing line
            GW.shape.editMapFeature.setStrokeStyle({color:color});
            GW.shape.editMapFeature.setFillStyle({color:color});
        } else {                                                                // new line
            GW.mapDiv.map.showFeature( GW.shape.editFeature, true );            // put the line on the map
        }
        GW.dirty = true;                                                        // mark the page as dirty
        GW.shape.editFeature = null;                                            // clear the saved edit feature and mapfeature
        GW.shape.editMapFeature = null;
    },
    editDelete: function(){                                                     // delete exit from edit
        var r = confirm( 'Delete line?' );
        if( r ){
            GW.shape.editDialog.hide();
            GW.mapDiv.map.map.removeOverlay( GW.shape.editMapFeature );         // actually delete the feature from the map
            GW.dirty = true;                                                    // mark the page as dirty
            GW.shape.editFeature = null;                                        // clear the saved edit feature and mapfeature
            GW.shape.editMapFeature = null;
        }
    }
};
GW.kml = {                                                                      // kml delete support
};
GW.pageProperties = {                                                           // routines to support page properties
    dialog: null,
    init: function(){                                                           // init page properties dialogue panels
        GW.pageProperties.dialog = new YAHOO.widget.Dialog("idPagePropertiesDialog",
            { 
                postmethod: "none",
                fixedcenter : true,
                constraintoviewport: true,
                modal: true,
                visible : false, 
                buttons : [ 
                    { text:"Save", handler: function(){GW.pageProperties.save();}, isDefault:true },
                    { text:"Exit", handler: function(){this.cancel();}, isDefault:false } 
                ]
            });
        GW.pageProperties.dialog.render(document.body);
    },
    show: function(){                                                           // show the properties of this page
        GW.log.log('showPagePropertiesDialog');
        // put the page data in the form
        document.ppForm.pageTitle.value = GW.page['title'];
        document.ppForm.pageRevision.value = GW.page['revision'];
        document.ppForm.pageLocked.value = GW.page['locked'];
        document.ppForm.pageAuthor.value = GW.page['nickname'];
        document.ppForm.pageDate.value = GW.page['date'];
        //document.ppForm.pageTags.value = GW.serializeStringList( GW.page['tags'], '\n' );
        document.ppForm.pageTags.value = GW.page['tags'].join('; ');
        //document.ppForm.pageFeaturePages.value = GW.serializeStringList( GW.page['featurepages'], '\n' );
        document.ppForm.pageFeaturePages.value = GW.page['featurepages'].join('; ');
        //document.ppForm.pageFeatureTags.value = GW.serializeStringList( GW.page['featuretags'], '\n' );
        document.ppForm.pageFeatureTags.value = GW.page['featuretags'].join( '; ' );
        GW.pageProperties.dialog.bringToTop();
        GW.pageProperties.dialog.show();
        // todo: get tag and page lists dynamically
    },
    save: function(){                                                           // save the page properties
        GW.dirty = true;
        // fixme: get the tags, featurepages, and featuretags
        var tags = document.ppForm.pageTags.value;
        tags = tags.replace(/; /g, ";");
        tags = tags.split( ';' );
        GW.page['tags'] = tags;
        var fpages = document.ppForm.pageFeaturePages.value;
        fpages = fpages.replace(/; /g, ";");
        fpages = fpages.split( ';' );
        GW.page['featurepages'] = fpages;
        var ftags = document.ppForm.pageFeatureTags.value;
        ftags = ftags.replace(/; /g, ";");
        ftags = ftags.split( ';' );
        GW.page['featuretags'] = ftags;
        GW.pageProperties.dialog.hide();
    }
};
GW.rte = {                                                                      // rich text editor routines
    editor: null,
    config: {                                                                   // YUI RTE editor config
        width: '702px',
        height: '525px',
        animate: true,
        dompath: true,
        filterWord: true,
        resize: true,
        focusAtStart: true,
        //
        toolbar: {
            grouplabels: false,                                                 // turn off group labels
            buttons: [
                { group: 'fontstyle', label: ' ',
                    buttons: [
                        { type: 'select', label: 'Arial', value: 'fontname', disabled: true,
                            menu: [
                                { text: 'Arial', checked: true },
                                { text: 'Arial Black' },
                                { text: 'Comic Sans MS' },
                                { text: 'Courier New' },
                                { text: 'Lucida Console' },
                                { text: 'Tahoma' },
                                { text: 'Times New Roman' },
                                { text: 'Trebuchet MS' },
                                { text: 'Verdana' }
                            ]
                        },
                        { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
                    ]
                },
                { type: 'separator' },
                { group: 'parastyle', label: ' ',
                    buttons: [
                    { type: 'select', label: 'Normal', value: 'heading', disabled: true,
                        menu: [
                            { text: 'Normal', value: 'none', checked: true },
                            { text: 'Header 1', value: 'h1' },
                            { text: 'Header 2', value: 'h2' },
                            { text: 'Header 3', value: 'h3' },
                            { text: 'Header 4', value: 'h4' },
                            { text: 'Header 5', value: 'h5' },
                            { text: 'Header 6', value: 'h6' }
                        ]
                    }
                    ]
                },
                { type: 'separator' },
                { group: 'textstyle', label: ' ',
                    buttons: [
                        { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
                        { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
                        { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
                        { type: 'separator' },
                        { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
                        { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
                        { type: 'separator' },
                        { type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true },
                        { type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' }
                    ]
                },
                { type: 'separator' },
                { group: 'alignment', label: ' ',
                    buttons: [
                        { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
                        { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
                        { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
                        { type: 'push', label: 'Justify', value: 'justifyfull' }
                    ]
                },
                { type: 'separator' },
                { group: 'indent', label: ' ',
                    buttons: [
                        { type: 'push', label: 'Indent', value: 'indent', disabled: true },
                        { type: 'push', label: 'Outdent', value: 'outdent', disabled: true }
                    ]
                },
                { type: 'separator' },
                { group: 'list', label: ' ',
                    buttons: [
                        { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
                        { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
                    ]
                },
                { type: 'separator' },
                { group: 'insertitem', label: ' ',
                    buttons: [
                        { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true },
                        { type: 'push', label: 'Insert Image', value: 'insertimage' }
                    ]
                }
            ]
        }
    },
    init: function(){                                                           // init the RTE for editing the page content
        GW.rte.editor = new YAHOO.widget.Editor('idContent', GW.rte.config );
        GW.rte.editor.render();
        GW.rte.editor.on( 'editorContentLoaded', GW.rte.init2 );
    },
    init2: function(){                                                          // finish rte initialization
        GW.log.log( 'rte init2' );
        GW.rte.editor.setEditorHTML( GW.page['content'] );                      // set content
        var div = document.getElementById( 'idLeft' );                          // the div holding the RTE
        var th = (GW.rte.editor.toolbar.get('element').clientHeight + 2);       // It has a 1px border.
        var dh = (GW.rte.editor.dompath.clientHeight + 1);                      // It has a 1px top border.
        var newH = (div.clientHeight - th - dh);
        GW.rte.editor.set('width', div.clientWidth - 2 + 'px' );                // ????? don't know why 2 px correction is needed but it works
        GW.rte.editor.set('height', newH - 12 - 1 + 'px');                      // ????? don't know why 1 px correction is needed but it works
        GW.log.log( 'rte h ' + GW.vpHeight() + ' ' + GW.menu.height + ' ' + th + ' ' + dh + ' ' + newH);
    }
};

if( typeof console != 'undefined' ){ console.debug('edit.js'); }
